<template>
  <div class="page-modal">
    <el-dialog
      v-model="dialogVisible"
      destroy-on-close
      :title="pageModalConfig.title || ''"
      :width="useMainStore().layoutConfig.shrink ? '90%' : '60%'"
      draggable
    >
      <hmyForm v-bind="pageModalConfig" v-model="formData">
        <template v-for="item in data" :key="item.fileId" #[item.slotName]>
          <slot :name="item.slotName"></slot>
        </template>
      </hmyForm>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="cancel">取消</el-button>
          <el-button type="primary" @click="handleCreateUser"> 确定 </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, watch } from 'vue'
import usePageContentStore from '@/stores/page-content/page-content'
import useMainStore from '@/stores/main/main'
import hmyForm from '@/base-ui/form'

interface IPageModelProps {
  pageModalConfig: any
  defaultInfo?: any
  otherInfo?: any
}
const props = withDefaults(defineProps<IPageModelProps>(), {
  pageModalConfig: () => ({}),
  defaultInfo: () => ({}),
  otherInfo: () => ({})
})

// 循环子孙传过来的自定义插槽
const data = props.pageModalConfig.formItems.filter(
  (item: any) => item.slotName
)

// 输入框基本数据
let formData = ref<any>({})
watch(
  () => props.defaultInfo,
  () => {
    for (const item of props.pageModalConfig.formItems) {
      formData.value[item.fileId] = props.defaultInfo[item.fileId]
    }
  }
)

// 弹窗控制
const dialogVisible = ref(false)
const pageContentStore = usePageContentStore()
const cancel = () => {
  dialogVisible.value = false
}
//点击弹窗确定按钮
const handleCreateUser = async () => {
  if (Object.keys(props.defaultInfo).length) {
    pageContentStore.editAction(
      props.pageModalConfig.pageName,
      { ...formData.value, ...props.otherInfo },
      props.defaultInfo.id
    )
  } else {
    if (props.otherInfo.imgUrl) {
      const res = await pageContentStore.createAction(
        props.pageModalConfig.pageName,
        {
          ...formData.value,
          ...props.otherInfo
        }
      )
      await pageContentStore.uploadImgAction(
        props.pageModalConfig.pageName,
        res.data.insertId,
        props.otherInfo.imgUrl
      )
    } else {
      await pageContentStore.createAction(props.pageModalConfig.pageName, {
        ...formData.value,
        ...props.otherInfo
      })
    }
  }
  dialogVisible.value = false

  // 重新加载数据,刷新下拉刷新框的数据

  switch (props.pageModalConfig.pageName) {
    case 'role':
      useMainStore().getRoleDataAction()
      break
    case 'department':
      useMainStore().getDepartmentDataAction()
      break
    case 'menber':
      useMainStore().getMenberDataAction()
      break
    default:
      break
  }
}

defineExpose({ dialogVisible })
</script>

<style lang="less" scoped></style>
